package com.ja.openchat.ui.chat;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.ViewModelProviders;

import com.ja.openchat.ui.chat.group.GroupChatSettingsSingleActivity;
import com.zy.openchat.core.model.config.AppConfigInfo;

import com.blankj.utilcode.util.BarUtils;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityChatBinding;
import com.ja.openchat.ui.OuterShareActivity;
import com.ja.openchat.ui.chat.group.GroupChatSettingsNewActivity;
import com.ja.openchat.ui.contact.ContactChatSettingsActivity;
import com.ja.openchat.viewmodels.ChatViewmodel;
import com.lxj.xpopup.util.XPopupUtils;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.GroupSendInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.ScreenShotListenManager;
import com.zy.openchat.util.ScreenshotListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

public class ChatActivity extends BaseActivity<ActivityChatBinding, ChatViewmodel> implements ScreenShotListenManager.OnScreenShotListener {

    private ConversationFragment conversationFragment;
    private ChatInfo conversation;
    private ScreenshotListener screenShotListenManager;//截屏监听相关
    private GroupSendInfo groupSendInfo = null;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_chat;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            BarUtils.setStatusBarColor(this, Color.WHITE);
        } else {
            BarUtils.setStatusBarColor(this, Color.BLACK);
        }
        BarUtils.setStatusBarLightMode(this, true);
    }

    @Override
    public ChatViewmodel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(ChatViewmodel.class);
    }


    public static void startActivity(Context context, ChatInfo chatInfo){
        Intent intent = new Intent(context,ChatActivity.class);
        intent.putExtra("conversation", chatInfo);
        if (!(context instanceof Activity)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void startActivity(Activity context, GroupSendInfo sendInfo,int requestCode){
        if(sendInfo==null||sendInfo.isEmpty()){
            return;
        }
        Intent intent = new Intent(context,ChatActivity.class);
        intent.putExtra("userInfos", sendInfo);
        if (!(context instanceof Activity)) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivityForResult(intent,requestCode);
    }


    @Override
    public void initView() {
        super.initView();
        OuterShareActivity.isStartMain = true;
        conversation = getIntent().getParcelableExtra("conversation");
        if(getIntent().getSerializableExtra("userInfos")!=null){
            groupSendInfo = (GroupSendInfo) getIntent().getSerializableExtra("userInfos");
        }
        binding.toolbar.ivBarRight.setVisibility(View.GONE);
        if(groupSendInfo!=null&&!groupSendInfo.isEmpty()){
            if(conversation==null){
                conversation = groupSendInfo.buildChat();
            }
            binding.toolbar.userAvatarRight.setVisibility(View.GONE);
            binding.toolbar.userAvatarRight1.setVisibility(View.GONE);
        }else{
//            binding.toolbar.userAvatarRight.setVisibility(View.VISIBLE);
            binding.toolbar.userAvatarRight1.setVisibility(View.VISIBLE);
        }

        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.toolbar.tvOkRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(conversationFragment!=null){
                    conversationFragment.toggleConversationMode();
                }
            }
        });
        binding.toolbar.userAvatarRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(conversation != null){
                    if(conversation.isGroup()){
                        GroupChatSettingsNewActivity.start(ChatActivity.this, conversation);
                    }else{
                        ContactChatSettingsActivity.start(ChatActivity.this, conversation);
                    }
                }
            }
        });
        binding.toolbar.userAvatarRight1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(conversation != null){
                    if(conversation.isGroup()){
                        GroupChatSettingsSingleActivity.start(ChatActivity.this, conversation);
                    }else{
                        ContactChatSettingsActivity.start(ChatActivity.this, conversation);
                    }
                }
            }
        });
        binding.toolbar.ivBarRight1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(conversationFragment!=null) {
                    conversationFragment.toggleToCall();
                }
            }
        });
        binding.toolbar.tvOkRight.setText(getString(R.string.cancle_text));
        conversationFragment = new ConversationFragment();
        handleChat(true);
        Bundle bundle = new Bundle();
        bundle.putParcelable("conversation",conversation);
        bundle.putSerializable("userInfos",groupSendInfo);
        conversationFragment.setArguments(bundle);
        getSupportFragmentManager().beginTransaction()
                .add(R.id.containerFrameLayout, conversationFragment, "content")
                .commit();
        viewModel.setConversationFragment(conversationFragment);
//
        setChatUnReadNum(UserInfo.getUserInfo().msgUnreadTotalCount);
        handleTitleBtns();
        registerScreenShotListener();
    }

    private void handleChat(boolean isOpen){
        if(conversation == null){
            return;
        }
        long chatId = conversation.id;
        TelegramManager.getTelegramManager().handleChat(this, chatId, isOpen, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {

            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        });
    }

    private void handleTitleBtns(){
        if(conversation != null){
            if(conversation.isMyFovChat()){
                binding.toolbar.userAvatarRight.setVisibility(View.GONE);
                binding.toolbar.userAvatarRight1.setVisibility(View.GONE);
                binding.toolbar.ivBarRight1.setVisibility(View.GONE);
            }else {
                if(conversation.isGroup()){
                    binding.toolbar.userAvatarRight.showGroup(conversation);
                }else if(conversation.isPrivateChat()||conversation.isSecretChat()){
                    UserInfo userInfo = UserInfo.getUserInfo(conversation.userId());
                    if(userInfo!=null){
                        binding.toolbar.userAvatarRight.showUser(userInfo);
                    }else{
                        TelegramManager.getTelegramManager().getUserSimpleInfo(conversation.userId());
                    }
                }
                binding.toolbar.ivBarRight1.setVisibility(View.GONE);
            }
            if(conversation.isSecretChat()){
                binding.toolbar.tvBarTitle.setCompoundDrawablePadding(XPopupUtils.dp2px(this,5));
                binding.toolbar.tvBarTitle.setCompoundDrawablesWithIntrinsicBounds(null,null,ContextCompat.getDrawable(this,R.mipmap.icon_private),null);
            }else {
                binding.toolbar.tvBarTitle.setCompoundDrawablesWithIntrinsicBounds(null,null,null,null);
            }
        }
    }


    public void setChatUnReadNum(long unReadNum){
        if(unReadNum>0){
            binding.toolbar.unreadNumText.setVisibility(View.VISIBLE);
            binding.toolbar.unreadNumText.setText(String.valueOf(unReadNum));
        }else{
            binding.toolbar.unreadNumText.setVisibility(View.GONE);
        }

    }



    @Override
    public void onShot(String imagePath) {
        if(conversationFragment!=null){
            conversationFragment.sendScreenshot();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(conversation!=null){
            TelegramManager.getTelegramManager().getTgData().setCurChatId(conversation.id);
        }
        if(screenShotListenManager!=null){
            screenShotListenManager.startListening();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(screenShotListenManager!=null){
            screenShotListenManager.stopListening();
        }
    }

    public void setSubTitle(String subTitle){
        AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
        if(configInfo==null||configInfo.shown_online_members){
            if(TextUtils.isEmpty(subTitle)){
                binding.toolbar.tvBarBottomTitle.setVisibility(View.GONE);
            }else{
                binding.toolbar.tvBarBottomTitle.setText(subTitle);
                binding.toolbar.tvBarBottomTitle.setVisibility(View.VISIBLE);
                binding.toolbar.tvBarBottomBlueTitle.setVisibility(View.GONE);
            }

            if(groupSendInfo!=null&&!groupSendInfo.isEmpty()){
                binding.toolbar.tvBarBottomTitle.setVisibility(View.GONE);
            }
        }else{
            binding.toolbar.tvBarBottomTitle.setVisibility(View.GONE);
        }

    }

    public void setInputSubTitle(String subTitle){
        if(TextUtils.isEmpty(subTitle)){
            binding.toolbar.tvBarBottomBlueTitle.setVisibility(View.GONE);
            binding.toolbar.tvBarBottomTitle.setVisibility(View.VISIBLE);
        }else{
            binding.toolbar.tvBarBottomBlueTitle.setText(subTitle);
            binding.toolbar.tvBarBottomBlueTitle.setVisibility(View.VISIBLE);
            binding.toolbar.tvBarBottomTitle.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handleChat(false);
        TelegramManager.getTelegramManager().getTgData().setCurChatId(0);
        if(screenShotListenManager!=null){
            // 注销监听
            screenShotListenManager.stopListening();
        }

    }

    @Override
    public void setTitle(CharSequence title) {
        binding.toolbar.tvBarTitle.setText(title);
    }

    public void setRightTitle(String value){
        if(TextUtils.isEmpty(value)){
            binding.toolbar.tvBarRightTitle.setVisibility(View.GONE);
        }else{
            binding.toolbar.tvBarRightTitle.setText(value);
            binding.toolbar.tvBarRightTitle.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onBackPressed() {
        if (!conversationFragment.onBackPressed()) {
            super.onBackPressed();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        ChatInfo chatInfo = intent.getParcelableExtra("conversation");
        if(chatInfo!=null&&conversation!=null&&chatInfo.id == conversation.id){
            long messageId = intent.getLongExtra("messageId",0);
            if(messageId!=0&&conversationFragment!=null){
                binding.containerFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(binding.containerFrameLayout==null){
                            return;
                        }
                        conversationFragment.scrollToMessagePositionById(messageId,true);
                    }
                },500);

            }
            return;
        }
        handleChat(false);
        conversation = chatInfo;
        if (conversation == null||conversationFragment==null) {
            finish();
            return;
        }
        handleChat(true);
        TelegramManager.getTelegramManager().getTgData().setCurChatId(conversation.id);
        conversationFragment.setupConversation(conversation);
        handleTitleBtns();
    }


    public void changeCancleBtnVisiable(boolean isShow){
        binding.toolbar.tvOkRight.setVisibility(isShow?View.VISIBLE:View.GONE);
        binding.toolbar.ivBarRight.setVisibility(isShow?View.GONE:View.VISIBLE);
//        binding.toolbar.userAvatarRight.setVisibility(isShow?View.GONE:View.VISIBLE);
        binding.toolbar.userAvatarRight1.setVisibility(isShow?View.GONE:View.VISIBLE);
        if(conversation != null&&!conversation.isGroup()){
            binding.toolbar.ivBarRight1.setVisibility(isShow?View.GONE:View.VISIBLE);
        }

    }

    /**
     * 注册截屏监听
     */
    private void registerScreenShotListener() {
        screenShotListenManager = new ScreenshotListener() {
            @Override
            public void onScreenshotDetected(String path) {
                onShot(path);
            }
        };

        if (Build.VERSION.SDK_INT > 22) {
            List<String> permissionList = new ArrayList<>();
            // 检查权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            } else {
                // 开始截图监听
                screenShotListenManager.startListening();
            }
            if (permissionList != null && (permissionList.size() != 0)) {
                ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), 0);
            }
        } else {
            // 开始截图监听
            screenShotListenManager.startListening();
        }
    }

    public void goProfileActivity() {
        viewModel.goProfileActivity();
    }
}
